package com.example.accessingdatajpa.service.impl;

import com.example.accessingdatajpa.pojo.Role;
import com.example.accessingdatajpa.repository.RoleRepository;
import com.example.accessingdatajpa.response.RestResponse;
import com.example.accessingdatajpa.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service("roleService")
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleRepository roleRepository;

    //find all roles
    @Override
    @Transactional
    public RestResponse<List<Role>> queryAllRoles(){
        RestResponse<List<Role>> response = new RestResponse<>();
        try {
            List<Role> data = roleRepository.findAll();
            response.setStatus(200);
            response.setMessage("查询成功");
            response.setData(data);
        }catch (RuntimeException e){
            response.setStatus(500);
            response.setMessage(e.getMessage());
        }
        return response;
    }
    //add a new role
    @Override
    @Transactional
    public RestResponse<String> addRoles(Role role){
            RestResponse<String> response = new RestResponse<>();
        try {
            roleRepository.save(role);
            response.setStatus(200);
            response.setMessage("ok");
            response.setData("保存成功");
        }catch (RuntimeException e){
            response.setStatus(500);
            response.setMessage(e.getMessage());
            response.setData("保存失败");
        }
        return response;
    }
}
